import { useRouter } from 'vue-router'
import { useTabsStore } from '@/store/modules/tabs'
interface NavigateOptions {
  name?: string
  query?: Record<string, any>
}
export function useCloseTabNavigate() {
  const router = useRouter()
  const { delVisitedRoute, visitedRoutes } = useTabsStore()

  const closeTabNavigate = async ({ name, query }: NavigateOptions = {}) => {
    const currentRoutes = visitedRoutes?.find((item) =>
      item?.path?.includes(router.currentRoute.value.path)
    )
    const currentPath = currentRoutes?.path || router.currentRoute.value.path

    if (currentPath) {
      await delVisitedRoute(currentPath)
    }

    if (!name) {
      const latestView = visitedRoutes
        .filter((_: any) => _.path !== currentPath)
        .slice(-1)[0]
      if (latestView) await router.push(latestView)
      else await router.push('/')
    } else {
      router.push({
        name,
        ...(query && { query }), // 如果 query 存在，则传递 query 参数
      })
    }
  }

  return {
    closeTabNavigate,
  }
}
